package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hanyun-admin/src/entity"
	"hanyun-admin/src/service"
	"hanyun-admin/src/utils"
	"net/http"
	"strconv"
	"time"
)

//用户列表
func GetSysUserList(c *gin.Context) {
	var user entity.User
	c.Bind(&user)
	userList := service.SelectSysUserList(user)
	count := service.SelectSysUserListCount(user)
	c.JSON(http.StatusOK, gin.H{
		"code":  http.StatusOK,
		"msg":   "操作成功",
		"row":   userList,
		"total": count,
	})
}

//新增按钮数据
func AddViewUserData(c *gin.Context) {
	roles := service.SelectRoleAll()
	posts := service.SelectPostAll()
	c.JSON(http.StatusOK, gin.H{
		"code":  http.StatusOK,
		"roles": roles,
		"posts": posts,
		"msg":   "操作成功",
	})
}

//保存新增数据
func AddSysUserData(c *gin.Context) {
	var user entity.User
	c.BindJSON(&user)
	user.CreateTime = time.Now()
}

//查询数据详情
func GetSysUserInfoByUserId(c *gin.Context) {
	userId, _ := strconv.ParseInt(c.Param("userId"), 10, 64)
	user := service.SelectSysUserInfoByUserId(userId)
	roles := service.SelectRoleAll()
	posts := service.SelectPostAll()
	postIds := service.SelectPostListByUserId(userId)
	roleIds := service.SelectRoleListByUserId(userId)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"data":    user,
		"roles":   roles,
		"posts":   posts,
		"postIds": postIds,
		"roleIds": roleIds,
	})
}

//重置用户密码
func UpdateUserPasswordByUserId(c *gin.Context) {
	var user entity.User
	c.Bind(&user)
	password, _ := utils.PasswordEncryption(user.Password)
	user.Password = password
	err := service.UpdateUserData(user)
	fmt.Print(user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "操作成功",
	})
}

//用户状态修改
func ChangeUserStatus(c *gin.Context) {
	var user entity.User
	c.Bind(&user)
	//效验是否可以操作
	if user.IsAdmin() {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "不允许操作超级管理员",
		})
		return
	}
	err := service.UpdateUserData(user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "操作成功",
	})
}
